import {Work} from '../../../db/models/work';
import {sendError, sendSuccess} from "../../utils/responseHandler";
import {WorkSeeker} from "../../../db/models/work_seekers";
import jwt from "jsonwebtoken";
import {User} from "../../../db/models/user";
import sequelize from "../../../db";
import {QueryTypes} from "sequelize";

export default async function handler(req, res) {
    if (req.method === 'POST') {
        try {
            const token = req.headers.authorization?.split(' ')[1];  // Bearer token
            if (!token) {
                sendError(res, '没有提供Token', 401);
                return;
            }

            const decoded = jwt.verify(token, 'linweifeng123456789');
            const user = await User.findByPk(decoded.id);
            if (!user) {
                sendError(res, '用户未找到', 404);
                return;
            }

            const {workId} = req.body;
            //找到该岗位有多少人报名
            const query = `SELECT u.*,js.status FROM db_users u INNER JOIN db_job_seekers js ON js.user_id = u.id WHERE js.work_id = :workId`;
            const seekersList = await sequelize.query(query, {
                replacements: {workId: workId},
                type:QueryTypes.SELECT
            });

            sendSuccess(res, seekersList);
        } catch (error) {
            if (error.name === 'JsonWebTokenError') {
                sendError(res, '无效的Token', 401);
            } else if (error.name === 'TokenExpiredError') {
                sendError(res, 'Token已过期', 500);
            } else {
                sendError(res, '内部服务器错误', 500);
            }
        }
    } else {
        res.setHeader('Allow', ['GET']);
        res.status(405).end('Method Not Allowed');
    }
}
